package com.yaxin.system.listener;


import cn.hutool.extra.spring.SpringUtil;
import com.yaxin.common.core.domain.entity.SysUser;
import com.yaxin.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 动态指定部门经理审批监听器
 */
@Slf4j
@Component
public class DeptLeaderTaskListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution execution) {
//        获取发起人id
        ProcessInstance processInstance = SpringUtil.getBean(RuntimeService.class)
            .createProcessInstanceQuery()
            .processInstanceId(execution.getProcessInstanceId())
            .singleResult();
        String startUserId = processInstance.getStartUserId();
        log.info("发起人id：{}", startUserId);

//    根据具体情况修改
        SysUserMapper userMapper = SpringUtil.getBean(SysUserMapper.class);
//        根据发起人id查询本部门的经理id
        List<SysUser> leaders = userMapper.getLeaderById(Long.valueOf(startUserId));


        List<String> ids = leaders.stream()
            .map(SysUser::getUserId) // 提取 SysUser 对象的 id 属性
            .map(String::valueOf) // 将 id 转换为字符串
            .collect(Collectors.toList()); // 将结果收集到 List<String> 中
        log.info("部门经理id：{}", ids);

        execution.setVariable("candidateUsers", ids); // 将计算得到的审批人设置为流程变量，多人审批只需一人通过就可以进行下一节点的审批流程
// 也可以使用assignee
        System.out.println("动态指定部门经理审批监听器执行完成");
    }

}

